package hzk.codex2016.list;

public class ListNode {
	public int val;
	public ListNode next;

	public ListNode(int x) {
		val = x;
		next = null;
	}

	public static ListNode asList(int[] vals, int n) {
		if (vals == null)
			return null;
		ListNode head = null, pre = null, p;
		for (int i = 0; i < n; i++) {
			p = new ListNode(vals[i]);
			if (head == null)
				head = p;
			if (pre != null)
				pre = pre.next = p;
			else
				pre = head;
		}
		return head;
	}

	public static ListNode asList(int... vals) {
		if (vals == null)
			return null;
		return asList(vals, vals.length);
	}

	public boolean isCircled() {
		int cnt = 0;
		ListNode p = this.next;
		while (p != null && ++cnt < 20000) {
			if (p == this)
				return true;
			p = p.next;
		}
		if (cnt == 20000)
			return true;
		return false;
	}

	public ListNode next(int index){
		ListNode p=this;
		while (p!=null && index-->0) p=p.next;
		return p;
	}
	
	
	public ListNode tail(){
		ListNode p=this;
		while (p.next!=null) p=p.next;
		return p;
	}
	
	public String toString() {
		ListNode p = this;
		boolean notFirst = false;
		StringBuffer sb = new StringBuffer();
		while (p != null) {
			if (notFirst && p == this) {
				sb.append("->(head)");
				break;
			}
			sb.append(p.val).append("->");

			notFirst = true;
			p = p.next;
		}
		if (p == null)
			sb.append("$");
		return sb.toString();
	}
}
